package com.jacobson.huobi.mvp.fragment

import android.app.ProgressDialog
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.alibaba.fastjson.JSONObject
import com.jacobson.core.di.components.AppComponent
import com.jacobson.huobi.Constants
import com.jacobson.huobi.R
import com.jacobson.huobi.common.BaseSelectableFragment
import com.jacobson.huobi.common.constants.UserTypeConstant
import com.jacobson.huobi.di.components.DaggerMeFragmentComponent
import com.jacobson.huobi.di.modules.MeFragmentModule
import com.jacobson.huobi.entities.UpdateInfo
import com.jacobson.huobi.entities.events.LoginEvent
import com.jacobson.huobi.entities.response.CommonResponse
import com.jacobson.huobi.entities.vo.LoginRespVo
import com.jacobson.huobi.mvp.*
import com.jacobson.huobi.mvp.contract.MeContract
import com.jacobson.huobi.threads.TokenThread
import com.jacobson.huobi.utils.ApkUtil
import com.jacobson.huobi.utils.DownLoadUtil
import com.jacobson.huobi.utils.TokenStorageUtil
import com.jacobson.huobi.websocket.ProtocolFactory
import com.jacobson.huobi.websocket.WebsocketManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_me.*
import org.simple.eventbus.Subscriber
import java.io.File

class MeFragment : BaseSelectableFragment<MeContract.Presenter>(), MeContract.View {

    private var isLogin = false
    private var loginRespVo: LoginRespVo? = null

    override fun setupFragmentComponent(appComponent: AppComponent) {
        DaggerMeFragmentComponent.builder()
            .appComponent(appComponent)
            .meFragmentModule(MeFragmentModule(this))
            .build()
            .inject(this)
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.fragment_me

    override fun initData(savedInstanceState: Bundle?) {
        initLoginInfo()
        initBtnClick()
        initItem()
        initUpdateInfo()

    }

    private fun initUpdateInfo() {
        presenter.loadUpdateInfo()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            initLoginInfo()
        }
    }

    override fun showUpdateDialog(response: CommonResponse<UpdateInfo>) {
        if (ApkUtil.getVersionCode(context!!) >= response.data.version_code) {
            return
        }
        AlertDialog.Builder(context!!)
            .setTitle("升级提示")
            .setMessage("有新的app版本，是否升级？")
            .setCancelable(false)
            .setNegativeButton(
                "下次升级"
            ) { dialog: DialogInterface?, which: Int -> }
            .setPositiveButton(
                "现在升级"
            ) { dialog: DialogInterface?, which: Int ->
                downloadAndUpgrade(
                    response.data
                )
            }
            .show()

    }

    private fun downloadAndUpgrade(updateInfo: UpdateInfo) {
        val url: String = updateInfo.getDownload_url()
        val saveDir = context!!.externalCacheDir

        if (!saveDir.exists()) {
            saveDir.mkdir()
        }
        val progressDialog = ProgressDialog(context)
        progressDialog.setTitle("下载中")
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
        progressDialog.max = 100
        progressDialog.setCancelable(false)
        progressDialog.show()

        val file = File(
            saveDir,
            "CeLueRen_" + updateInfo.getVersion_name() + System.currentTimeMillis() + ".apk"
        )
        val subscribe = DownLoadUtil.download(url, file.absolutePath)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext { integer: Int? ->
                progressDialog.progress = integer!!
            }
            .ignoreElements()
            .subscribe(
                {
                    progressDialog.dismiss()
                    ApkUtil.installApk(
                        context!!,
                        "com.jacobson.huobi.FILE_PROVIDER",
                        file.absolutePath
                    )
                }
            ) { throwable: Throwable? ->
                Toast.makeText(
                    context!!,
                    "更新失败，请重试",
                    Toast.LENGTH_SHORT
                ).show()
            }
    }

    @Subscriber
    private fun onUpdate(loginEvent: LoginEvent) {
        if (loginEvent.type == 1) {
            initLoginInfo()
        } else {
            logger.d("实时刷新token")
            presenter.refreshToken()
        }
    }

    override fun onRefreshTokenResultResp(response: CommonResponse<JSONObject>) {

        if (response.code == Constants.RESP_OK && !response.data.isNullOrEmpty()) {
            var data = response.data
            var userTokenInfo = TokenStorageUtil.readJsonData()
            if (userTokenInfo == null) {
                TokenStorageUtil.save("")
                Toast.makeText(this.context, "请先登录!", Toast.LENGTH_SHORT).show()
                LoginActivity.startActivity(context!!)
                return
            }
            userTokenInfo.put("access_token", data.getString("accessToken"))
            userTokenInfo.put("refresh_token", data.getString("refreshToken"))
            userTokenInfo.put("refresh_times", System.currentTimeMillis())
            TokenStorageUtil.save(userTokenInfo.toJSONString())
            TokenThread.start()
            WebsocketManager.sendMessage(ProtocolFactory.ofCommitAccessToken(data.getString("accessToken")))
        } else {//refresh_token 过期
            TokenStorageUtil.save("")
            Toast.makeText(this.context, "请重新登录!", Toast.LENGTH_SHORT).show()
            LoginActivity.startActivity(context!!)
            return
        }
        initLoginInfo()

    }

    override fun onLoadNoticeLatestResultResp(response: CommonResponse<List<JSONObject>>) {
        var noticeContent = "公告:"
        if (response.code == Constants.RESP_OK) {
            println(response)
            val dataList = response.data
            if (dataList.isNullOrEmpty()) {
                llMeNotice.visibility = View.GONE
                return
            } else {
                var dataInfo = dataList[0]
                noticeContent += dataInfo.getString("content")
                if (!dataInfo.getString("content").isNullOrEmpty() && isLogin) {
                    llMeNotice.visibility = View.VISIBLE
                } else {
                    llMeNotice.visibility = View.GONE
                }
            }
        } else {
            llMeNotice.visibility = View.GONE
        }
        tvMeNotice.text = noticeContent
    }

    private fun initBtnClick() {
//        btnKYCAuth.isClickable = true
        logger.d("开始初始化我的页面")
        btnLogin.setOnClickListener {
            logger.d("进入登陆")
            LoginActivity.startActivity(this.context!!)
        }

        btnKYCAuth.setOnClickListener {
            if (!isLogin) {
                Toast.makeText(this.context, "请先登录!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            logger.d("进入kyc认证")
            KycAuthActivity.startActivity(this.context!!)
        }

        btnRenevalMember.setOnClickListener {
            if (!isLogin) {
                Toast.makeText(this.context, "请先登录!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            RenevalMemberActivity.startActivity(this.context!!)
            logger.d("进入续费会员")
        }
        btnInviteFriends.setOnClickListener {
            if (!isLogin) {
                Toast.makeText(this.context, "请先登录!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            InviteFriendsActivity.startActivity(this.context!!)
            logger.d("进入邀请好友")
        }
        btnContactUs.setOnClickListener {
            ContactUsActivity.startActivity(this.context!!)
            logger.d("进入联系我们")
        }
        editPassword.setOnClickListener {
            if (!isLogin) {
                Toast.makeText(this.context, "请先登录!", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            EditPasswordActivity.startActivity(this.context!!)
            logger.d("进入修改密码")
        }
        editSoftware.setOnClickListener {
            EditSoftwareActivity.startActivity(this.context!!)
            logger.d("进入软件设置")
        }
        btnAboutCelueren.setOnClickListener {
            AboutCeluerenActivity.startActivity(this.context!!)
            logger.d("进入策略机器人")
        }
        btnQuantitativeRobot.setOnClickListener {
            Toast.makeText(this.context, "政策思路，敬请期待!", Toast.LENGTH_SHORT).show()
            logger.d("进入量化机器人")
        }
        btnGotoHelp.setOnClickListener {

            HelpWebViewActivity.startActivity(this.context!!)
        }

    }

    private fun initLoginInfo() {
        //读取登陆用户信息
        loginRespVo = TokenStorageUtil.read()
        if (loginRespVo != null) {
            isLogin = true
            btnLogin.visibility = View.GONE
            tvMeUserName.visibility = View.VISIBLE
            llUserIdAndLevel.visibility = View.VISIBLE
            tvMeUserName.text = "HI," + loginRespVo!!.nickName
            tvMeUserId.text = "UID:" + loginRespVo!!.userId
            tvVIPLevel.text = UserTypeConstant.getUserTypeDesc(loginRespVo!!.vipLevel)
        } else {
            isLogin = false
            btnLogin.visibility = View.VISIBLE
            tvMeUserName.visibility = View.GONE
            llUserIdAndLevel.visibility = View.GONE
        }
        if (isLogin) {
//            llMeNotice.visibility = View.VISIBLE
            presenter.loadNoticeLatest()
        }
    }

    private fun initItem() {
        tvMeNotice.isSelected = true
    }

    override fun onError(type: Int, extra: Any?, code: Int, message: String): Boolean {
//        TokenStorageUtil.save("")
//        initLoginInfo()
        logger.e("error >>> $message")
        Toast.makeText(this.context, "$message", Toast.LENGTH_SHORT).show()
        return super.onError(type, extra, code, message)
    }

    companion object {
        fun newInstance(): MeFragment {
            return MeFragment()
        }
    }
}